package com.weilele.leisure.time.ui.fragment


import android.os.Bundle

import androidx.activity.OnBackPressedCallback
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.DiffUtil
import com.weilele.base.library.BaseBindingFragment
import com.weilele.base.library.FragmentContainerActivity
import com.weilele.leisure.time.R
import com.weilele.leisure.time.databinding.FragmentHomeBinding

import com.weilele.mvvm.base.livedata.appCompatActivity
import com.weilele.mvvm.base.helper.createActivityViewModel
import com.weilele.mvvm.base.livedata.LiveDataWrap
import com.weilele.mvvm.base.livedata.wrapSuccessObserver
import com.weilele.mvvm.utils.activity.toast


class HomeFragment : BaseBindingFragment<FragmentHomeBinding>() {
    companion object {
        fun open(appCompatActivity: AppCompatActivity) {
            FragmentContainerActivity.start<HomeFragment>(appCompatActivity)
        }
    }

    private val homeViewModel by lazy { createActivityViewModel<HomeViewModel>() }

    private val pageAdapter by lazy { HomePageAdapter(this) }
    override fun initUi(savedInstanceState: Bundle?) {
        super.initUi(savedInstanceState)
        initPage()
    }


    private fun initPage() {
        mBinding.viewPager2.isUserInputEnabled = false
        mBinding.viewPager2.offscreenPageLimit = 3
        mBinding.bottomBar.setupWithViewPager(mBinding.viewPager2)
        mBinding.bottomBar.setBottomNavigateAdapter(HomeMenuAdapter(pageAdapter.pages))
        mBinding.viewPager2.adapter = pageAdapter
    }


    override fun getObserverLiveData(): List<LiveDataWrap>? {
        return listOf(homeViewModel.pagesData wrapSuccessObserver ::onPageData)
    }

    /**
     * 当首页数据发生变化
     */
    private fun onPageData(pages: MutableList<HomePageBean>) {
        val old = pageAdapter.pages.toList()
        pageAdapter.pages.clear()
        pageAdapter.pages.addAll(pages)
        val new = pageAdapter.pages
        DiffUtil.calculateDiff(HomePagesDiffCall(old,new)).dispatchUpdatesTo(pageAdapter)
    }


    private var lastClickTime = 0L
    override fun onBackPressed(): OnBackPressedCallback? {
        return object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                val currentTime = System.currentTimeMillis()
                if (currentTime - lastClickTime <= 2000L) {
                    appCompatActivity?.finishAfterTransition()
                } else {
                    lastClickTime = currentTime
                   R.string.click_again_to_back_tips.toast()
                }
            }
        }
    }
}